<!-- #layout name=blank -->
<div id="app" v-cloak>
  <div class="page-header">
    <h1 class="title">Forms</h1>
  </div>
  <kb-breadcrumb :breads="breads"></kb-breadcrumb>
  <div class="navbar navbar-default">
    <div class="container-fluid">
      <a class="btn green navbar-btn" :href="Kooboo.Route.Form.DetailPage"
        >Create a form</a
      >
      <a :href="Kooboo.Route.Form.KooFormPage" class="btn green navbar-btn"
        >Create Kform</a
      >
      <a
        class="btn red navbar-btn"
        v-show="selectedRows.length>0"
        @click="onDelete"
        >Delete</a
      >
    </div>
  </div>
  <ul class="nav nav-tabs">
    <li
      v-for="(item,index) in tabs"
      :key="index"
      :class="{active:item.value==currentTab}"
    >
      <a href="javascript:;" @click="onTabClick(item.value)"
        >{{ item.displayName }}</a
      >
    </li>
  </ul>
  <kb-table :data="model" show-select :selected.sync="selectedRows">
    <kb-table-column :label="Kooboo.text.common.name" prop="name">
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.data">
      <template v-slot="row">
        <a class="badge blue" target="_blank" :href="getDataUrl(row.id)">
          {{ row.valueCount }}
        </a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.usedBy">
      <template v-slot="row">
        <a
          class="label label-sm kb-table-label-refer"
          :style="{
                      background: Kooboo.getLabelColor(item.key.toLowerCase())
                    }"
          v-for="(item, index) in Kooboo.objToArr(row.references)"
          :key="index"
          @click.stop="onShowRelationModal(item.key, row.id, Kooboo.Form.name)"
        >
          {{ item.value + " " +
          Kooboo.text.component.table[item.key.toLowerCase()] }}
        </a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.lastModified">
      <template v-slot="row">
        <span>
          {{ new Date(row.lastModified).toDefaultLangString() }}
        </span>
      </template>
    </kb-table-column>

    <kb-table-column align="right" width="200px">
      <template v-slot="row">
        <a class="btn blue" :href="getEditUrl(row)" @click.stop=""
          >{{ Kooboo.text.common.edit }}</a
        >
        <a class="btn btn-primary" @click.stop="onSettingClick(row.id)"
          >{{ Kooboo.text.common.setting }}</a
        >
      </template>
    </kb-table-column>
  </kb-table>
  <kb-relation-modal></kb-relation-modal>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showSettingModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button data-dismiss="modal" class="close"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">Setting</h4>
        </div>
        <div class="modal-body" v-if="showSettingModal">
          <kb-form :model="settingModel">
            <kb-form-item>
              <label class="control-label col-md-3">Enable</label>
              <div class="col-md-9">
                <kb-switch v-model="settingModel.enable"></kb-switch>
              </div>
            </kb-form-item>
            <div v-kb-collapsein="settingModel.enable">
              <kb-form-item>
                <label class="control-label col-md-3">Method</label>
                <div class="col-md-9">
                  <label class="radio-inline">
                    <input
                      type="radio"
                      value="get"
                      v-model="settingModel.method"
                    />Get
                  </label>
                  <label class="radio-inline">
                    <input
                      type="radio"
                      value="post"
                      v-model="settingModel.method"
                    />Post
                  </label>
                </div>
              </kb-form-item>
              <kb-form-item>
                <label class="control-label col-md-3">Redirect to</label>
                <div class="col-md-9">
                  <select
                    class="form-control"
                    v-model="redirectUrl"
                    :class="{'margin-bottom-10':redirectUrl=='__external_link'}"
                  >
                    <option
                      v-for="(item,index) in linkList"
                      :key="index"
                      :value="item.path"
                    >
                      {{ item.name }}
                    </option>
                  </select>
                  <input
                    type="text"
                    class="form-control"
                    placeholder="External link address"
                    v-model="externalUrl"
                    v-show="redirectUrl=='__external_link'"
                  />
                </div>
              </kb-form-item>
              <kb-form-item>
                <label class="control-label col-md-3">Submitter</label>
                <div class="col-md-9">
                  <select
                    v-model="settingModel.formSubmitter"
                    class="form-control"
                  >
                    <option
                      v-for="(item,index) in availableSubmitters"
                      :value="item.name"
                      >{{ item.name }}</option
                    >
                  </select>
                </div>
              </kb-form-item>

              <kb-form-item v-if="settings.length>0">
                <label class="control-label col-md-3">Setting</label>
                <div class="col-md-9">
                  <div class="col-md-12">
                    <kb-form-item v-for="(item,index) in settings" :key="index">
                      <label class="control-label"
                        >{{ item.name &&
                        Kooboo.text.component.table[item.name.toLowerCase()]
                        }}</label
                      >
                      <input
                        v-if="item.controlType=='TextBox'"
                        type="text"
                        class="form-control"
                        v-model="item.defaultValue"
                      />
                      <textarea
                        v-else-if="item.controlType=='TextArea'"
                        class="form-control"
                        v-model="item.defaultValue"
                      ></textarea>
                      <select
                        v-else
                        class="form-control"
                        v-model="item.defaultValue"
                      >
                        <option
                          v-for="(op,i) in item.selectionValues"
                          :key="i"
                          :value="op.key"
                          >{{ op.value }}</option
                        >
                      </select>
                    </kb-form-item>
                  </div>
                </div>
              </kb-form-item>
            </div>
          </kb-form>
        </div>
        <div class="modal-footer">
          <button @click="saveSettingModal" class="btn green">Save</button>
          <button data-dismiss="modal" class="btn gray">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  Kooboo.loadJS([
    "/_Admin/Scripts/components/kbBreadcrumb.js",
    "/_Admin/Scripts/components/kbForm.js",
    "/_Admin/Scripts/components/kbTable.js",
    "/_Admin/Scripts/components/kbRelationModal.js",
    "/_Admin/Scripts/lib/bootstrap-switch/bootstrap-switch.min.js",
    "/_Admin/Scripts/components/kbSwitch.js"
  ]);
  Kooboo.loadCSS([
    "/_Admin/Scripts/lib/bootstrap-switch/bootstrap-switch.min.css"
  ]);

  new Vue({
    el: "#app",
    data: function() {
      return {
        breads: [
          {
            name: "SITES"
          },
          {
            name: "DASHBOARD"
          },
          {
            name: Kooboo.text.common.Forms
          }
        ],
        tabs: [
          {
            displayName: Kooboo.text.common.external,
            value: "External"
          },
          {
            displayName: Kooboo.text.common.Embedded,
            value: "Embedded"
          }
        ],
        currentTab: location.hash === "#Embedded" ? "Embedded" : "External",
        model: [],
        selectedRows: [],
        showSettingModal: false,
        settingModel: {
          id: "",
          formId: "",
          method: "get",
          redirectUrl: "",
          setting: {},
          formSubmitter: "",
          enable: false
        },
        pageList: [],
        redirectUrl: "",
        externalUrl: "",
        showExternalLinkInput: false,
        availableSubmitters: []
      };
    },
    mounted: function() {
      var me = this;
      this.onTabClick(me.currentTab);
      Kooboo.Page.getAll().then(function(res) {
        if (res.success) {
          me.pageList = res.model.pages;
        }
      });
    },
    computed: {
      linkList: function() {
        return [
          {
            name: Kooboo.text.site.form.refreshSelf,
            path: "RefreshSelf()"
          }
        ]
          .concat(this.pageList)
          .concat([
            {
              name: Kooboo.text.common.externalLink,
              path: "__external_link"
            }
          ]);
      },
      settings: function() {
        var me = this;
        var formSubmitter = this.availableSubmitters.find(function(f) {
          return f.name == me.settingModel.formSubmitter;
        });
        if (!formSubmitter) return [];
        formSubmitter.settings.forEach(function(i) {
          if (!i.defaultValue && i.selectionValues.length > 0) {
            i.defaultValue = i.selectionValues[0].key;
          }
        });
        return formSubmitter.settings;
      }
    },
    methods: {
      onTabClick(value) {
        var me = this;
        Kooboo.Form["get" + value + "List"]().then(function(res) {
          if (res.success) {
            me.model = res.model;
            me.currentTab = value;
            me.selectedRows = [];
          }
        });
      },
      getDataUrl: function(id) {
        return Kooboo.Route.Get(Kooboo.Route.Form.ValuePage, {
          id: id
        });
      },
      onShowRelationModal: function(by, id, type) {
        Kooboo.EventBus.publish("kb/relation/modal/show", {
          by: by,
          type: type,
          id: id
        });
      },
      getEditUrl: function(row) {
        var editUrl = "";
        if (
          this.currentTab.toLowerCase() == "embedded" ||
          row.formType.toLowerCase() == "normal"
        ) {
          editUrl = Kooboo.Route.Form.DetailPage;
        } else if (row.formType.toLowerCase() == "koobooform") {
          editUrl = Kooboo.Route.Form.KooFormPage;
        }
        return Kooboo.Route.Get(editUrl, { Id: row.id });
      },
      onSettingClick: function(id) {
        var me = this;
        Kooboo.Form.getSetting({
          id: id
        }).then(function(res) {
          me.settingModel.id = res.model.id;
          me.settingModel.formId = res.model.formId;
          me.settingModel.method = res.model.method || "get";
          me.externalUrl = "";
          me.settingModel.enable = res.model.enable;
          var redirectUrl = me.linkList.find(function(f) {
            return f.path == res.model.redirectUrl;
          });
          if (redirectUrl) {
            me.redirectUrl = res.model.redirectUrl;
          } else {
            if (res.model.redirectUrl == null) {
              me.redirectUrl = me.linkList[0].path;
            } else {
              me.externalUrl = res.model.redirectUrl;
              me.redirectUrl = "__external_link";
            }
          }
          me.availableSubmitters = res.model.availableSubmitters;
          me.availableSubmitters.forEach(function(formSubmitter) {
            formSubmitter.settings.forEach(function(item) {
              item.selectionValues = Kooboo.objToArr(item.selectionValues);
            });
          });
          me.settingModel.formSubmitter =
            res.model.formSubmitter || me.availableSubmitters[0].name;

          me.showSettingModal = true;
        });
      },
      saveSettingModal: function() {
        var me = this;
        Kooboo.Form.updateSetting(this.settingModel).then(function(res) {
          if (res.success) {
            window.info.show(Kooboo.text.info.update.success, true);
            me.showSettingModal = false;
          } else {
            window.info.show(Kooboo.text.info.update.fail, false);
          }
        });
      },
      onDelete: function() {
        var me = this;
        var haveRelations = this.selectedRows.some(function(s) {
          return s.references && Object.keys(s.references).length;
        });

        var confirmStr = haveRelations
          ? Kooboo.text.confirm.deleteItemsWithRef
          : Kooboo.text.confirm.deleteItems;

        var ids = this.selectedRows.map(function(m) {
          return m.id;
        });

        if (!confirm(confirmStr)) return;

        Kooboo[Kooboo.Form.name]
          .Deletes({
            ids: ids
          })
          .then(function(res) {
            if (res.success) {
              me.onTabClick(me.currentTab);
              window.info.done(Kooboo.text.info.delete.success);
            } else {
              window.info.done(Kooboo.text.info.delete.fail);
            }
          });
      }
    },
    watch: {
      redirectUrl: function(value) {
        if (value == "__external_link") {
          this.settingModel.redirectUrl = this.externalUrl;
        } else {
          this.settingModel.redirectUrl = value;
        }
      },
      externalUrl: function(value) {
        this.settingModel.redirectUrl = value;
      },
      settings: {
        handler: function(value) {
          var me = this;
          this.settingModel.setting = {};
          value.forEach(function(i) {
            me.settingModel.setting[i.name] = i.defaultValue;
          });
        },
        deep: true
      }
    }
  });
</script>
